#include <sys/types.h>
#include "base64.h"

size_t base64_encode (const char *input, size_t len, char *output, size_t break_lines)
{
	static const char base64chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

	const unsigned char *in;
	char *out;
	unsigned padding;
	size_t linelen;
	int i, to;

	in = (const unsigned char *) input;
	out = output;
	padding = len % 3;
	linelen = 0;
	to = len - padding;

	for (i = 0; i < to; i += 3) {
		if (break_lines) {
			if (linelen > break_lines) {
				*out++ = '\r';
				*out++ = '\n';

				linelen = 0;
			}
		}

		*out++ = base64chars[in[0] >> 2];
		*out++ = base64chars[((in[0] & 3) << 4) | (in[1] >> 4)];
		*out++ = base64chars[((in[1] & 15) << 2) | (in[2] >> 6)];
		*out++ = base64chars[in[2] & 63];

		linelen += 4;
		in += 3;
	}

	if (padding) {
		*out++ = base64chars[in[0] >> 2];
		if (padding == 1) {
			*out++ = base64chars[((in[0] & 3) << 4)];
			*out++ = '=';
		} else {
			*out++ = base64chars[((in[0] & 3) << 4) | (in[1] >> 4)];
			*out++ = base64chars[((in[1] & 15) << 2)];
		}

		*out++ = '=';
	}

	*out = 0;

	return (out - output);
}
